using MultiAgentsClient.Service.WorkflowEngine.BaseNodes;
using MultiAgentsShared;

namespace MultiAgentsClient.Service.WorkflowEngine.BuiltInNodes;

/// <summary>
/// No toolcall for parameter extraction request
/// </summary>
public class NodeParameterExtractionRequest(string nodeId) : NodeRequestToService(nodeId)
{
    public string Context = "";
    public List<string> Descriptions = [];
}

public class NodeParameterExtractionResponse(string nodeId) : NodeResponseFromService(nodeId)
{
    public List<string> ParameterValues = [];
}

[NodeGraphPortDef(1, 1)]
public class ParameterExtractionNode : ServiceDependentNode<NodeParameterExtractionRequest, NodeParameterExtractionResponse>
{
    public class ParameterDescription
    {
        public string Description { get; set; } = "";
        public string Name { get; set; } = "";
    }

    [NodeGraphParam] public string Context = "";
    [NodeGraphParam] public List<ParameterDescription> ParameterDescriptions = [];
    private string ContextRuntime => InsertVariable(Context);

    public ParameterExtractionNode() : base() { }

    protected override NodeOutcome ServiceResponseHandler(NodeParameterExtractionResponse cmd)
    {
        Debug.LogLine("LlmSwitchNodeResponse:" + cmd.ParameterValues);

        if (cmd.ParameterValues.Count == ParameterDescriptions.Count)
        {
            for (int i = 0; i < ParameterDescriptions.Count; i++)
            {
                runtimeContext.SetVar(Id, ParameterDescriptions[i].Name, cmd.ParameterValues[i]);
            }
        }

        return new NodeOutcome(NodeOutcomeStatus.Success, 0);
    }

    protected override void SendRequestToService()
    {
        List<string> descriptions = [];
        descriptions.AddRange(ParameterDescriptions.Select(parameterDescription => parameterDescription.Description));
        NodeParameterExtractionRequest nodeParameterExtractionRequest = new(Id)
        {
            Context = ContextRuntime,
            Descriptions = descriptions,
        };

        EventBus.Publish(nodeParameterExtractionRequest);
    }
}
